<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :areas="treeAreas" :area-type="areaType"  v-on:handleNodeClick="onHandleNodeClick" />
      </el-col>
      <el-col :span="20" :xs="24">
        <div class="filter-container">
      <el-input v-model="listQuery.terminal_number" class="filter-item" clearable
                placeholder="终端编号" style="width: 200px"/>
      <el-input v-model="listQuery.upgrade_no" class="filter-item" style="margin-left: 20px;width: 200px" clearable
                placeholder="升级批次号" />
      <el-select v-model="listQuery.status" class="filter-item" clearable placeholder="升级状态"
                   style="margin-left: 20px;width: 110px">
          <el-option
            v-for="(item,idx) in statusList"
            :key="idx"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      <el-button  class="filter-item" icon="el-icon-search" style="margin-left:40px;"
                 type="primary"
                 @click="fetchData">
        查询
      </el-button>
      <el-button  class="filter-item" icon="el-icon-upload" style="margin-left:20px;" type="primary"
                  @click="handleImport">导入</el-button>
      <el-button  class="filter-item" icon="el-icon-close" style="margin-left:20px;" type="danger"
                  @click="handleCancel">撤销升级</el-button>
          <el-button  class="filter-item" icon="el-icon-download" :loading="btnLoading" style="margin-left:10px"
                        type="primary"
                        @click="handleExport">
              导出
            </el-button>
    </div>
    <el-divider />
    <el-table
      key="ota-upgrade"
      ref="ota"
      v-loading="listLoading"
      :cell-style="{padding:0+'px'}"
      :data="list"
      :row-style="{height:40+'px'}"
      border
      fit
      height="700"
      highlight-current-row
      stripe
      style="width: 100%;"
    >
      <el-table-column
        type="selection"
        :selectable="handleSelect"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column align="center" label="升级批次号">
        <template v-slot="{row}">
          <span>{{ row.upgrade_batch.UpgradeNo }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="升级版本号">
        <template v-slot="{row}">
          <span>{{ row.upgrade_batch.upgrade_version }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="表号">
        <template v-slot="{row}">
          <span>{{ row.terminal_number }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="IEMI" >
        <template v-slot="{row}">
          <span>{{ row.iemi_id }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="升级区域" >
        <template v-slot="{row}">
          <span>{{ row.upgrade_area }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="升级状态" width="80">
        <template v-slot="{row}">
          <span :class="row.upgrade_status | statusColor ">{{ row.upgrade_status | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="升级下发时间" width="80">
        <template v-slot="{row}">
          <span>{{ row.updated_at | dateTimeFormat  }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="升级结果" >
        <template slot-scope="{row}">
          <span>{{ row.upgrade_result ? row.upgrade_result:'-'  }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                @pagination="fetchData"/>
      </el-col>
    </el-row>

    <el-dialog title="导入" :visible.sync="dialogImportVisible" custom-class="window-small-width" :close-on-click-modal="false">
      <el-form ref="importForm" :rules="importForm.rules" :model="importForm.model" v-loading="formLoading" element-loading-text="正在导入数据，请稍后"
               element-loading-spinner="el-icon-loading" label-position="right" label-width="60px">
        <el-form-item label="" prop="version" >
          <el-input v-model="importForm.model.version" class="filter-item" style="width: 200px" clearable
                    placeholder="版本号" />
        </el-form-item>
        <el-form-item label="" prop="files" >
          <el-upload
            ref="upload"
            key="ota-upload"
            multiple
            action="/meter/ota/upgrade"
            :on-change="fileChange"
            :onl-remove="fileRemove"
            :auto-upload="false"
            :file-list="files"
          >
            <el-button slot="trigger" size="small" type="primary">选取Excel和升级程序</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">
          取消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="importSubmit">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import {cancelOtaUpgrade, importOtaUpgrade, otaUpgradeHistory} from "@/api/ota";
import Pagination from '@/components/Pagination'
import {getToken} from "@/utils/auth";
import {getAreaTree} from "@/api/area";
import moment from "moment";
import {exportExcel} from "@/utils/excel";

const statusList = [
        {label:'等待',value:0},
        {label:'升级中',value:1},
        {label:'成功',value:2},
        {label:'失败',value:3},
        {label:'已取消',value:4},
        {label:'全部',value:-1}
      ]

export default {
  name: "Ota",
  components: { areas,Pagination },
  data() {
    const checkFiles = (rule, value, callback) => {
      console.log(this.files)
      if (this.files.length < 2) {
        return callback(new Error('请上传设备数据和升级主程序'));
      }else {
        return callback();
      }
    };
    return {
      listLoading: false,
      formLoading: false,
      btnLoading: false,
      dialogImportVisible: false,
       areaType:2,
      listQuery: {
        terminal_number: null,
        upgrade_no: null,
         area_code:'',
        status:-1,
        pageSize: 20,
        page: 1
      },
      importData: {},
        treeAreas:[],
      list: [],
      files: [],
      total: 0,
      token:'',
      //'等待', '升级中','成功', '失败','已取消'
      statusList:statusList,
      fileTypes:['application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
      importForm: {
        rules: {
          version: [
            { required: true, message: '请输入升级程序版本号', trigger: 'blur' }
          ]
        },
        model: {
          version: null,
        }
      }
    }
  },
  filters: {
    statusText(val) {
      const t = statusList.find(item=>{
        return  item.value === val
      })
      return t ? t.label : '-'
    },
    statusColor(val) {
      const t = ['default', 'upgrading','success', 'failed','cancel']
      return t[val]
    },
    dateTimeFormat(t){
      if(!t) {
        return '-'
      }
      return moment(t).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  created() {
    this.fetchData()
    this.getAreaTree()
    this.token = getToken()
  },
  methods: {
    fetchData() {
      otaUpgradeHistory(this.listQuery).then(res => {
        if (res.code === 20000) {
          this.list = res.data.list
          this.total = res.data.total
        }
      })
    },
    getAreaTree(){
      getAreaTree({type:2}).then(response => {
        this.treeAreas = response.data
      })
    },
    download(row) {
      const url = window.location.host + '/meter/ota/file?id='+row.upgrade_id
      window.open(url)
    },
    handleSelect(row){
      return row.upgrade_status === 0
    },
    handleImport() {
      this.importForm.model.version = null
      this.dialogImportVisible = true
      this.$nextTick(() => {
        this.$refs.importForm.clearValidate()
        this.$refs.upload.clearFiles()
      })
    },
    importSubmit() {
      this.$refs['importForm'].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.append('version',this.importForm.model.version)
          this.files.forEach((file) => {
            formData.append('files',file.raw)
          })
          this.btnLoading = true
          importOtaUpgrade(formData).then(res => {
            if(res.code === 20000){
              this.dialogImportVisible = false
              this.fetchData()
            }else{
              this.$message.error(res.message)
            }
          }).catch((err) => {
            this.$message.error(err)
          }).finally(() => {
            this.$refs.upload.clearFiles()
            this.btnLoading = false
          })
        } else {
          return false;
        }
      });
    },
    onHandleNodeClick:function (data) {
      if(this.listQuery.area_code !== data.code){
        this.listQuery.area_code = data.code
        this.fetchData()
      }
    },
    fileChange(file,fileList) {
      this.files = fileList
    },
    fileRemove(file,fileList) {
      this.files = fileList
    },
    handleCancel() {
      const rows = this.$refs.ota.selection
      if(rows.length === 0){
        this.$message.error('请选择需要撤销升级的设备')
        return
      }
      let ids = []
      rows.forEach(function (row) {
        ids.push(row.id)
      })
      this.$confirm('是否确认取消所选设备的升级', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelOtaUpgrade({ids:ids}).then(res => {
          if (res.code === 20000) {
            this.fetchData()
          }
        })
      })
    },
     handleExport() {
      this.btnLoading = true
      let query = Object.assign({}, this.listQuery)
      query.pageSize = 50000
      otaUpgradeHistory(query).then(response => {
        const headers = ['批次号','版本号','表号','IEMI','升级区域','升级状态','下发时间','升级结果']
        const data = response.data.list.map(item => ({
          批次号: item.upgrade_batch.UpgradeNo,
          版本号: item.upgrade_batch.upgrade_version,
          表号: item.terminal_number,
          IEMI: item.iemi_id,
          升级区域: item.upgrade_area,
          升级状态: this.statusList.find(t=>{ return t.value === item.upgrade_status}).label,
          下发时间: moment(item.updated_at).format('YYYY-MM-DD HH:mm:ss'),
          升级结果: item.upgrade_result
        }))
        exportExcel(data, headers, 'OTA升级记录')
        setTimeout(() => {
          this.btnLoading = false
        }, 1.5 * 1000)
      })
    },
  }
}
</script>

<style scoped>
.upgrading {
  color: blue;
}
.failed {
  color: red;
}
.success {
  color: green;
}
.cancel {
  color: grey;
}
</style>
